package org.sample.algorithm.dining;

/**
 * Created by alan on 2017/7/12.
 */
public abstract class AbstractPhilosopher implements Runnable {

    protected String name;

    protected AbstractChopstick left;

    protected AbstractChopstick right;

    private int count = 0;

    public AbstractPhilosopher(String name, AbstractChopstick left, AbstractChopstick right) {
        this.name = name;
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
//        while (true) {
        for (int i = 0; i < 100; i++) {
            thinking();
            eating();
        }
    }

    public final void thinking() {
        System.out.println(name + " 正在思考");
        sleep();
    }

    public final void eating() {
        if (useChopsticks()) {
            count++;
            System.out.println(name + " 正在用餐");
            sleep();
        }
    }

    public abstract boolean useChopsticks();

    public int getCount() {
        System.out.println(name + "用餐" + count + "次");
        return count;
    }

    protected static void sleep() {
        try {
            Thread.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}